package cn.edu.paisi.controller;


import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@CrossOrigin
public class UploadController {
	@Value("${IMG_PATH}")
	private String IMG_PATH;
	
	@RequestMapping(value="/upload")
	public Map<String,String> uploadImg(MultipartFile file, 
			HttpServletResponse response,
			HttpServletRequest request) {
		MultipartFile uploadFile = file;
		response.setCharacterEncoding("UTF-8");
		Map<String, String> map = new HashMap<>();
		try {
			String originalFilename = uploadFile.getOriginalFilename();//获取源文件名
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); //取源文件名的扩展名
			String name = UUID.randomUUID().toString().replaceAll("-", "");//生成随机字符串作为新的文件名
			String newName = name + "." + extName; //新文件名
			uploadFile.transferTo(new File(IMG_PATH + newName)); //保存文件到指定的目录
			map.put("code", "0");
			map.put("location",  newName);
			map.put("msg","上传图片成功");    
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "500");
			map.put("msg","上传图片失败");
		}
		return map;
	}
}
